import type { CustomRequestOptions } from '@/interceptors/request'
import { useUserStore } from '@/stores'

const request = <T = any>(options: CustomRequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      success(response: UniApp.RequestSuccessCallbackResult) {
        // 状态码 2xx
        if (response.statusCode >= 200 && response.statusCode < 300) {
          // 2.1 提取核心数据 res.data
          return resolve((response.data as Response<T>).data)
        }
        // 根据后端错误信息轻提示
        if (!options.silence) {
          uni.showToast({
            icon: 'none',
            title: (response.data as Response<T>).message || '请求错误',
          })
        }
        if (response.statusCode === 401) {
          useUserStore().logout()
          return reject(new Error('登录信息失效，请重新登录'))
        }
        // 其他错误
        return reject(response)
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        })
        reject(err)
      },
    })
  })
}

const get = <T = any>(url: string, params?: object, config?: CustomRequestOptions): Promise<T> => {
  return request({
    method: 'GET',
    url,
    params,
    ...config,
  })
}

const post = <T = any>(url: string, params?: object, config?: CustomRequestOptions): Promise<T> => {
  return request({
    method: 'POST',
    url,
    data: params,
    ...config,
  })
}

const put = <T = any>(url: string, params?: object, config?: CustomRequestOptions): Promise<T> => {
  return request({
    method: 'PUT',
    url,
    data: params,
    ...config,
  })
}

const del = <T = any>(url: string, params?: object, config?: CustomRequestOptions): Promise<T> => {
  return request({
    method: 'DELETE',
    url,
    data: params,
    ...config,
  })
}

export default { get, post, put, del, request }
